import {Component, OnInit} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
import {Observable} from 'rxjs';
import {Http} from '@angular/http';
import {Router, ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-book-type-edit',
  templateUrl: './book-type-edit.component.html',
  styleUrls: ['./book-type-edit.component.css']
})
export class BookTypeEditComponent implements OnInit {

  formModel: FormGroup;
  private fb: FormBuilder = new FormBuilder();
  private bookType: any = {};

  private id: any;
  private dataSource: Observable<any>;
  responseErr: string;

  submit() {
    this.responseErr = '';
    if (this.formModel.hasError('required', ['typeCode'])) {
      this.responseErr = "未填写编码"
    } else if (this.formModel.hasError('required', ['typeName'])) {
      this.responseErr = "未填写名称"
    }
    if (this.formModel.valid) {
      this.dataSource = this.http.post('booktype/save', Object.assign(this.bookType, this.formModel.value)).map(res => res.json())
      this.dataSource.subscribe(data => {
        if (data.code === 0) {
          this.router.navigate(['book-type-list'])
        } else {
          this.responseErr = data.msg
        }
      });
    }
  }

  getDetail() {
    this.dataSource = this.http.post(`booktype/detail?id=${this.id}`, null).map(res => res.json())
    this.dataSource.subscribe(data => {
      if (data.code === 0) {
        this.bookType = data.data;
        this.formModel.setValue({
          typeCode: data.data.typeCode,
          typeName: data.data.typeName
        });
      } else {
        alert(data.msg)
      }
    });
  }

  constructor(private http: Http, private router: Router, private route: ActivatedRoute) {
    this.formModel = this.fb.group({
      typeCode: ['', [Validators.required]],
      typeName: ['', [Validators.required]]
    })

  }

  ngOnInit() {
    this.id = this.route.snapshot.paramMap.get('id');
    this.id !== 'add' && this.getDetail()
  }

}
